package com.isias.system.fillter;

import com.alibaba.fastjson.JSON;
import com.isias.common.result.Result;
import com.isias.common.result.ResultCodeEnum;
import com.isias.common.util.JwtHelper;
import com.isias.common.util.ResponseUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Security;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 认证解析token过滤器
 * </p>
 */
public class TokenAuthenticationFilter extends OncePerRequestFilter {
    private RedisTemplate redisTemplate;
    public TokenAuthenticationFilter() {
    }

    public TokenAuthenticationFilter(RedisTemplate redisTemplate){
        this.redisTemplate=redisTemplate;
    }
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        logger.info("uri:"+httpServletRequest.getRequestURI());
        //如果是登录接口或者注册接口，直接放行
        if ("/admin/system/index/login".equals(httpServletRequest.getRequestURI())||"/admin/system/index/register".equals(httpServletRequest.getRequestURI())||"/admin/system/index/getCaptcha".equals(httpServletRequest.getRequestURI())){
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            return;
        }

        UsernamePasswordAuthenticationToken authentication = getAuthentication(httpServletRequest);
        if (null != authentication){
            SecurityContextHolder.getContext().setAuthentication(authentication);
            filterChain.doFilter(httpServletRequest,httpServletResponse);
        }else {
            ResponseUtil.out(httpServletResponse, Result.build(null, ResultCodeEnum.PERMISSION));
        }


    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request){
        //从请求头里获取token
        String token = request.getHeader("token");
        logger.info("token:"+token);
        //判断有没有token，如果有，就取出username，并判断username是否为空，如果不为空，就返回UsernamePasswordAuthenticationToken对象
        if (!StringUtils.isEmpty(token)){
            String username = JwtHelper.getUsername(token);
            logger.info("username:"+username);
            if (!StringUtils.isEmpty(username)){
                String authoritiesString = (String) redisTemplate.opsForValue().get(username);
                List<Map> mapList = JSON.parseArray(authoritiesString, Map.class);
                List<SimpleGrantedAuthority> authorities = new ArrayList<>();
                for (Map map : mapList) {
                    authorities.add(new SimpleGrantedAuthority((String)map.get("authority")));
                }
                return new UsernamePasswordAuthenticationToken(username,null, authorities);
            }
        }
        return null;

    }




}
